import React, { useEffect, useMemo, useState } from 'react';
import { Space, Form, Select, Tabs, Card } from 'antd';
import HomeTemplate from './template/HomeTemplate';
import PhotoTemplate from './template/PhotoTemplate';
import InsTemplate from './template/InsTemplate';
import InsEditTemplate from './template/InsEditTemplate';
import UploadTemplate from './template/UploadTemplate';
import AiTemplate from './template/AiTemplate';
import PrintPreviewTemplate from './template/PrintPreviewTemplate';

const { Option } = Select;

export default function ScreenSetting({ form }) {
  // 监听 machineFunction，用于控制模版 Tab 的显示
  const machineFunction = Form.useWatch('machineFunction', form);

  // 屏幕方向
  const dirOptions = useMemo(() => ([
    { value: 'portrait', label: '竖屏' },
    { value: 'landscape', label: '横屏' },
  ]), []);

  const [activeTab, setActiveTab] = useState('printPreview');

  const getFirstAvailableTab = () => {
    const mf = machineFunction || [];
    return 'printPreview';
  };

  useEffect(() => {
    setActiveTab(getFirstAvailableTab());
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [JSON.stringify(machineFunction)]);

  // 读取、写入 Form 的工具
  const saveCanvasToForm = (key, canvasData) => {
    if (form) {
      form.setFieldsValue({ [key]: JSON.stringify(canvasData) });
    }
  };

  const readCanvasFromForm = (key) => {
    try {
      const raw = form?.getFieldValue(key);
      return raw ? JSON.parse(raw) : { layers: [], canvasSize: { width: 270, height: 480 } };
    } catch (e) {
      return { layers: [], canvasSize: { width: 270, height: 480 } };
    }
  };

  const makeTemplateProps = (configKey) => {
    const canvas = readCanvasFromForm(configKey);
    return {
      layerList: canvas.layers || [],
      selectedLayer: null,
      basicInsertInfo: { machineFunction: mf },
      onLayerUpdated: (layers) => {
        saveCanvasToForm(configKey, { ...canvas, layers });
      },
      onLayerSelected: () => {},
      onCanvasSaved: (canvasData) => saveCanvasToForm(configKey, canvasData),
      onCanvasCleared: () => saveCanvasToForm(configKey, { layers: [], canvasSize: { width: 270, height: 480 } }),
    };
  };

  const mf = Array.isArray(machineFunction) ? machineFunction : [];

  return (
    <Space direction="vertical" style={{ width: '100%' }}>


      {/* 机器功能（多选，禁用，仅回显） */}
      <Form.Item name="machineFunction" label="机器功能">
        <Select mode="multiple"  placeholder="自动回显" style={{ width: '100%' }}>
          <Option value="1">拍照</Option>
          <Option value="2">Ins</Option>
          <Option value="3">扫码上传</Option>
          <Option value="6">AI</Option>
        </Select>
      </Form.Item>

      {/* 屏幕方向 */}
      <Form.Item name="machineScreenDirection" label="屏幕方向">
        <Select options={dirOptions} placeholder="请选择" style={{ width: '100%' }} />
      </Form.Item>

      {/* 模版配置 Tabs */}
      <Card size="small" title="界面模版配置">
        <Tabs activeKey={activeTab} onChange={setActiveTab} type="line">
          {mf.length > 1 && (
            <Tabs.TabPane tab="首页模版" key="home">
              <HomeTemplate {...makeTemplateProps('templateCustomConfig')} />
            </Tabs.TabPane>
          )}
          {mf.includes('1') && (
            <Tabs.TabPane tab="拍照模版" key="photo">
              <PhotoTemplate {...makeTemplateProps('homePageCustomConfig')} />
            </Tabs.TabPane>
          )}
          {mf.includes('2') && (
            <Tabs.TabPane tab="Ins模版" key="ins">
              <InsTemplate {...makeTemplateProps('insCustomConfig')} />
            </Tabs.TabPane>
          )}
          {mf.includes('2') && (
            <Tabs.TabPane tab="Ins编辑模版" key="insEdit">
              <InsEditTemplate {...makeTemplateProps('insEditCustomConfig')} />
            </Tabs.TabPane>
          )}
          {mf.includes('3') && (
            <Tabs.TabPane tab="扫码上传模版" key="upload">
              <UploadTemplate {...makeTemplateProps('scanCodeUploadCustomConfig')} />
            </Tabs.TabPane>
          )}
          {mf.includes('6') && (
            <Tabs.TabPane tab="AI模版" key="ai">
              <AiTemplate {...makeTemplateProps('aiTemplateCustomConfig')} />
            </Tabs.TabPane>
          )}
          <Tabs.TabPane tab="打印预览模版" key="printPreview">
            <PrintPreviewTemplate {...makeTemplateProps('printPreviewCustomConfig')} />
          </Tabs.TabPane>
        </Tabs>
      </Card>
    </Space>
  );
}